package com.ruoyi.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.TaskConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.TypeEnums;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StatusUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.handler.TaskHandler;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.constant.TaskConstants.TASK_SUBMIT_PIC;
import static com.ruoyi.common.constant.TaskConstants.TASK_SUBMIT_TEXT;

/**
 * 【请填写功能名称】Service接口
 *
 * @author ruoyi
 * @date 2024-04-16
 */
@Service
public class TaskServiceImpl implements TaskService {
    @Resource
    private ITBaseInfoService baseInfoService;
    @Resource
    private ITTaskInfoService taskInfoService;
    @Resource
    private ITTaskPicService taskPicService;
    @Resource
    private ITTaskBaseService taskBaseService;
    @Resource
    private ITUserInfoService userInfoService;
    @Resource
    private TaskHandler taskHandler;
    @Resource
    private TVipMapper vipMapper;
    @Resource
    private TUserTaskInfoMapper userTaskInfoMapper;
    @Resource
    private TUserMoneyChangeMapper moneyChangeMapper;
    @Resource
    private SysDictDataMapper dictDataMapper;

    @Override
    public void addBaseInfo(TBaseInfo baseInfo) {
        int i = baseInfoService.addBaseInfo(baseInfo);
    }

    @Override
    public void updateBaseInfo(TBaseInfo baseInfo) {
        Long id = baseInfo.getId();
        if (Objects.isNull(id)) {
            throw new ServiceException("修改信息id不能为空");
        }
        baseInfoService.updateTBaseInfo(baseInfo);
    }

    @Override
    public AjaxResult selectBaseInfo(TBaseInfoDto baseInfo) {
        PageHelper.startPage(baseInfo);
        List<TBaseInfo> list = baseInfoService.selectListByCondition(baseInfo);
        PageInfo<TBaseInfo> page = new PageInfo<>(list);
        return AjaxResult.success(page);
    }

    @Override
    public void addTaskInfo(TTaskInfoDto tTaskInfoDto) {
        TTaskInfo  tTaskInfo= new TTaskInfo();
        BeanUtils.copyProperties(tTaskInfoDto,tTaskInfo);
        tTaskInfo.setAuditStatus(1);
        tTaskInfo.setAbjectNum(0);
        tTaskInfo.setShelfStatus(1);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        tTaskInfo.setCreateBy(loginUser.getUsername());
        tTaskInfo.setUpdateBy(loginUser.getUsername());
        Date nowTime = new Date();
        tTaskInfo.setCreateTime(nowTime);
        tTaskInfo.setVersion(0);
        tTaskInfo.setAbjectNum(0);
        tTaskInfo.setFinishNum(0);
        tTaskInfo.setUpdateTime(nowTime);
        tTaskInfo.setIsDelete(0);
        TTaskInfo tTaskInfo1 = taskInfoService.addTaskInfo(tTaskInfo);
        // 标签的信息主要是标签的id
        List<TBaseInfoDto> baseInfos = tTaskInfoDto.getBaseDtoList();
        updateTaskBase(baseInfos, tTaskInfo1.getId());
        List<TTaskPicDto> taskPicList = tTaskInfoDto.getTaskPicList();
        updateTaskPic(taskPicList, tTaskInfo1.getId());
    }

    /**
     * 处理任务标签
     *
     * @param baseInfos
     * @param id
     */
    private void updateTaskBase(List<TBaseInfoDto> baseInfos, Long id) {
        if (!CollectionUtils.isEmpty(baseInfos)) {
            List<TTaskBase> ta = baseInfos.stream().map(v -> {
                TTaskBase tTaskBase = new TTaskBase();
                tTaskBase.setBaseId(v.getId());
                tTaskBase.setTaskId(id);
                return tTaskBase;
            }).collect(Collectors.toList());
            taskBaseService.saveBatch(ta);
        }
    }

    /**
     * 处理任务流程步骤图
     *
     * @param picDtoList
     * @param id
     */
    private void updateTaskPic(List<TTaskPicDto> picDtoList, Long id) {
        if (!CollectionUtils.isEmpty(picDtoList)) {
            List<TTaskPic> ta = picDtoList.stream().map(v -> {
                TTaskPic tTaskPic = new TTaskPic();
                BeanUtils.copyProperties(v, tTaskPic);
                tTaskPic.setIsDelete(0);
                tTaskPic.setType(1);
                tTaskPic.setTaskId(id);
                return tTaskPic;
            }).collect(Collectors.toList());
            taskPicService.saveBatch(ta);
        }
    }

    @Override
    public void updateTaskInfo(TTaskInfoDto taskInfoDto) {
        if (taskInfoDto.getId() == null) {
            throw new ServiceException("修改信息id不能为空");
        }
        TTaskInfo tTaskInfo = taskInfoService.getById(taskInfoDto.getId());
        if (tTaskInfo == null) {
            throw new ServiceException("修改信息不存在。");
        }
        TTaskInfo newTask = new TTaskInfo();
        BeanUtils.copyProperties(taskInfoDto, newTask);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        newTask.setUpdateBy(loginUser.getUsername());
        Date nowTime = new Date();
        newTask.setUpdateTime(nowTime);
        taskInfoService.updateById(newTask);
        List<TBaseInfoDto> baseInfos = taskInfoDto.getBaseDtoList();
        // 处理步骤图片
        List<TTaskPicDto> taskPicList = taskInfoDto.getTaskPicList();
        taskPicList.stream().forEach(v->{
            v.setType(1);
            v.setIsDelete(0);
        });
        taskPicService.deleteByTaskId(taskInfoDto.getId());
        this.updateTaskPic(taskPicList, taskInfoDto.getId());
        // 处理任务标签
        taskBaseService.deleteByTaskId(taskInfoDto.getId());
        this.updateTaskBase(baseInfos, taskInfoDto.getId());

    }

    @Override
    public AjaxResult selectTaskInfo(ConditionReq req) {
        Long lobbyTaskTypeId = req.getLobbyTaskTypeId();
        if (lobbyTaskTypeId != null) {
            TTaskBase tTaskBase = new TTaskBase();
            tTaskBase.setBaseId(lobbyTaskTypeId);
            List<TTaskBase> tTaskBases = taskBaseService.selectTTaskBaseList(tTaskBase);
            if (CollectionUtils.isEmpty(tTaskBases)) {
                PageHelper.startPage(req);
                List<TTaskInfoDto> homeTaskByType = new ArrayList<>();
                PageInfo<TTaskInfoDto> tTaskInfoDtoPageInfo = new PageInfo<>(homeTaskByType);
                return AjaxResult.success(tTaskInfoDtoPageInfo);
            }
            List<Long> taskIds = tTaskBases.stream().map(TTaskBase::getTaskId).collect(Collectors.toList());
            req.setTaskIds(taskIds);
        }
        PageHelper.startPage(req);
        List<TTaskInfoDto> homeTaskByType = taskInfoService.getHomeTaskByType(req);
        PageInfo<TTaskInfoDto> tTaskInfoDtoPageInfo = new PageInfo<>(homeTaskByType);
        return AjaxResult.success(tTaskInfoDtoPageInfo);
    }

    @Override
    public AjaxResult auditTaskInfo(TTaskInfoDto taskInfo) {
        // 用户截取任务id
        TUserTaskInfo tUserTaskInfo = userTaskInfoMapper.selectById(taskInfo.getId());
        if (tUserTaskInfo == null) {
            throw new ServiceException("该任务不存在");
        }
        Integer auditStatus1 = tUserTaskInfo.getAuditStatus();
        if (!auditStatus1.equals(2)){
            throw new ServiceException("当前任务不需要审核");
        }

        TTaskInfo t = auditTaskInfoCheckBaseInfo(taskInfo);
        Integer auditStatus = taskInfo.getAuditStatus();
        if (auditStatus.equals(0)){
            tUserTaskInfo.setReason(taskInfo.getReason());
            tUserTaskInfo.setAuditStatus(0);
        }
        if (auditStatus.equals(3)){
            tUserTaskInfo.setAuditStatus(3);
           // 审核通过
            computeMoney(t,tUserTaskInfo);
            // 完成数量+1
            taskInfoService.addFinishOne(t);
        }
        userTaskInfoMapper.updateById(tUserTaskInfo);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult auditSysTaskInfo(TTaskInfoDto taskInfo) {
        TTaskInfo t = auditTaskInfoCheckBaseInfo(taskInfo);
        Integer auditStatus = taskInfo.getAuditStatus();
        if (auditStatus.equals(0)){
            t.setRemark(taskInfo.getReason());
        }
        t.setAuditStatus(auditStatus);
        taskInfoService.updateById(t);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult auditShelfTaskInfo(TTaskInfoDto taskInfo) {
        TTaskInfo t = auditTaskInfoCheckBaseInfo(taskInfo);
        // 如果没有审核通过不允许下架
        Integer auditStatus = t.getAuditStatus();
        Integer shelfStatus = taskInfo.getShelfStatus();
        if (!auditStatus.equals(2)&&shelfStatus.equals(2)){
            throw new ServiceException("审核未通过不允许上架");
        }
        t.setShelfStatus(shelfStatus);
        taskInfoService.updateById(t);
        return AjaxResult.success();
    }



    /**
     * 获取首页任务列表-通过不同的数据来搜索
     * @return
     */
    @Override
    public AjaxResult getHomeTaskByType(ConditionReq req) {
        Long lobbyTaskTypeId = req.getLobbyTaskTypeId();
        if (lobbyTaskTypeId!=null){
            TTaskBase tTaskBase = new TTaskBase();
            tTaskBase.setBaseId(lobbyTaskTypeId);
            List<TTaskBase> tTaskBases = taskBaseService.selectTTaskBaseList(tTaskBase);
            if (CollectionUtils.isEmpty(tTaskBases)){
                return AjaxResult.success();
            }
            List<Long> taskIds = tTaskBases.stream().map(TTaskBase::getTaskId).collect(Collectors.toList());
            req.setTaskIds(taskIds);
        }
        PageHelper.startPage(req);
        List<TTaskInfoDto> homeTaskByType = taskInfoService.getHomeTaskByType(req);
        PageInfo<TTaskInfoDto> tTaskInfoDtoPageInfo = new PageInfo<>(homeTaskByType);
        return AjaxResult.success(tTaskInfoDtoPageInfo);
    }

    @Override
    public AjaxResult taskInfo(ConditionReq req) {
        Long taskId = req.getTaskId();
        if (Objects.isNull(taskId)){
            throw new ServiceException("任务id不能为空");
        }
        TTaskInfo taskInfo = taskInfoService.getById(taskId);
        if (Objects.isNull(taskInfo)){
            throw new ServiceException("任务不存在");
        }
        TTaskInfoDto tTaskInfoDto = new TTaskInfoDto();
        BeanUtils.copyProperties(taskInfo,tTaskInfoDto);
        // 获取任务标签
        List<Long> taskIds = Arrays.asList(taskId);
        List<TBaseInfoDto> tBaseInfoDtos = baseInfoService.selectPicByTaskIds(taskIds,4);
        tTaskInfoDto.setBaseDtoList(tBaseInfoDtos);
        //查看流程图
        List<TTaskPicDto> tTaskPicDtos = taskPicService.selectPicByTaskIds(taskIds,1);
        tTaskInfoDto.setTaskPicList(tTaskPicDtos);
        // 是否已截取任务
        List<TUserTaskInfo> tUserTaskInfos = userTaskInfoMapper.selectUserTask(taskId,SecurityUtils.getUserId());
        if (!CollectionUtils.isEmpty(tUserTaskInfos)){
            tTaskInfoDto.setAccessStatus(1);
            for (int i = 0; i < tUserTaskInfos.size(); i++) {
                if (i==0){
                    TUserTaskInfo tUserTaskInfo = tUserTaskInfos.get(0);
                    String reason = tUserTaskInfo.getReason();
                    tTaskInfoDto.setReason(reason);
                    tTaskInfoDto.setAuditStatus(tUserTaskInfo.getAuditStatus());
                }else {
                    Long id = tUserTaskInfos.get(i).getId();
                    userTaskInfoMapper.deleteTUserTaskInfoById(id);
                }
            }
        }
        return AjaxResult.success(tTaskInfoDto);
    }


    @Override
    public AjaxResult getUserTaskListStatistics() {
        // 获取个人任务完成状态的总数量
//        Long userId = SecurityUtils.getUserId();
//        List<TUser> userTaskInfoMapper.getUserTaskListStatistics(userId);
        return null;
    }





    @Override
    public AjaxResult sysTaskInfo(ConditionReq req) {
        Long taskId = req.getTaskId();
        if (Objects.isNull(taskId)) {
            throw new ServiceException("任务id不能为空");
        }
        TTaskInfo taskInfo = taskInfoService.selectTTaskInfoById(taskId);
        if (Objects.isNull(taskInfo)) {
            throw new ServiceException("任务不存在");
        }
        TTaskInfoDto tTaskInfoDto = new TTaskInfoDto();
        com.ruoyi.common.utils.bean.BeanUtils.copyBeanProp(tTaskInfoDto, taskInfo);
        // 默认任务为待提交
        tTaskInfoDto.setAuditStatus(1);
        // 获取任务标签
        List<Long> taskIds = Arrays.asList(taskId);
        List<TBaseInfoDto> demand = baseInfoService.selectPicByTaskIds(taskIds,4);
        tTaskInfoDto.setDemandList(demand);
        //查看流程图
        List<TTaskPicDto> tTaskPicDtos = taskPicService.selectPicByTaskIds(taskIds,1);
        tTaskInfoDto.setTaskPicList(tTaskPicDtos);

        return AjaxResult.success(tTaskInfoDto);
    }

    @Override
    public AjaxResult getBaseTag(TTaskInfoDto taskInfo) {
        TBaseInfoDto baseInfoDto = new TBaseInfoDto();
        baseInfoDto.setType(1);
        List<TBaseInfo> tBaseInfos = baseInfoService.selectListByCondition(baseInfoDto);
        return AjaxResult.success(tBaseInfos);
    }

    /**
     * 获取用户提交的任务和接受情况
     * @param taskInfo
     * @return
     */
    @Override
    public AjaxResult getUserTask(TTaskInfoDto taskInfo) {
        PageHelper.startPage(taskInfo);
        List<TUserTaskInfoAudit> userTask = taskInfoService.getUserTask(taskInfo);
        PageInfo<TUserTaskInfoAudit> tUserTaskInfoAuditPageInfo = new PageInfo<>(userTask);
        return AjaxResult.success(tUserTaskInfoAuditPageInfo);
    }

    @Override
    public AjaxResult getAuditUserInfo(TTaskInfoDto req) {
        Long taskId = req.getTaskId();
        if (Objects.isNull(taskId)) {
            throw new ServiceException("任务id不能为空");
        }
        TTaskInfo taskInfo = taskInfoService.selectTTaskInfoById(taskId);
        if (Objects.isNull(taskInfo)) {
            throw new ServiceException("任务不存在");
        }
        TTaskInfoDto tTaskInfoDto = new TTaskInfoDto();
        com.ruoyi.common.utils.bean.BeanUtils.copyBeanProp(tTaskInfoDto, taskInfo);
        // 默认任务为待提交
        tTaskInfoDto.setAuditStatus(1);
        // 获取任务标签
        List<Long> taskIds = Arrays.asList(taskId);
        List<TBaseInfoDto> demand = baseInfoService.selectPicByTaskIds(taskIds,4);
        tTaskInfoDto.setDemandList(demand);
        //查看流程图
        List<TTaskPicDto> tTaskPicDtos = taskPicService.selectPicByTaskIds(taskIds,1);
        tTaskInfoDto.setTaskPicList(tTaskPicDtos);
        Long userId = req.getUserId();
        if (userId == null){
            req.setUserId(SecurityUtils.getApiUser().getUserId());
        }
        // 是否已截取任务
        List<TUserTaskInfo> tUserTaskInfos = userTaskInfoMapper.selectUserTask(taskId, req.getUserId());
        if (!CollectionUtils.isEmpty(tUserTaskInfos)) {
            tTaskInfoDto.setAccessStatus(1);
            for (int i = 0; i < tUserTaskInfos.size(); i++) {
                if (i == 0) {
                    TUserTaskInfo tUserTaskInfo = tUserTaskInfos.get(0);
                    String reason = tUserTaskInfo.getReason();
                    tTaskInfoDto.setReason(reason);
                    tTaskInfoDto.setAuditStatus(tUserTaskInfo.getAuditStatus());
                    // 查看回显信息 接取任务时的数据
                    tTaskInfoDto.setPicVoucher(tUserTaskInfo.getPicVoucher());
                    tTaskInfoDto.setContentText(tUserTaskInfo.getContentText());
                    // 回显提交任务的数据
                    Long userTaskInfoId = tUserTaskInfo.getId();
                    List<TTaskPicDto> subPicList = taskPicService.selectPicByTaskIds(Arrays.asList(userTaskInfoId),2);
                    Map<Integer, List<TTaskPicDto>> taskPicMap = subPicList.stream().collect(Collectors.groupingBy(TTaskPicDto::getInfoType));
                    tTaskInfoDto.setSubmitTaskPicList(taskPicMap.get(1));
                    tTaskInfoDto.setSubmitTaskContentList(taskPicMap.get(2));
                } else {
                    Long id = tUserTaskInfos.get(i).getId();
                    userTaskInfoMapper.deleteTUserTaskInfoById(id);
                }
            }
        }else {
            tTaskInfoDto.setAccessStatus(2);
        }
        return AjaxResult.success(tTaskInfoDto);
    }

    private void checkSubmitTaskInfo(List<TTaskPicDto> taskPicList, TTaskInfo taskInfo) {
        Integer needInfo = taskInfo.getNeedInfo();
        Map<Integer, List<TTaskPicDto>> infoTypeMap = taskPicList.stream().collect(Collectors.groupingBy(TTaskPicDto::getInfoType));
        //1-图片，2-文字
        List<TTaskPicDto> tTaskPicDtoText = infoTypeMap.get(TASK_SUBMIT_TEXT);
        List<TTaskPicDto> tTaskPicDtoPic = infoTypeMap.get(TASK_SUBMIT_PIC);
        // 有对象还需要校验数据信息是否存在
        if (StatusUtil.Zero.equals(needInfo)){
            if (CollectionUtils.isEmpty(tTaskPicDtoText)){
                throw new ServiceException("请确认提交的审核信息");
            }if (CollectionUtils.isEmpty(tTaskPicDtoPic)){
                throw new ServiceException("请确认提交的审核信息");
            }
        }else if (StatusUtil.One.equals(needInfo)) {
            if (CollectionUtils.isEmpty(tTaskPicDtoText)){
                throw new ServiceException("请确认提交的审核信息");
            }
        }else if (StatusUtil.Two.equals(needInfo)) {
            if (CollectionUtils.isEmpty(tTaskPicDtoPic)){
                throw new ServiceException("请确认提交的审核信息");
            }
        }
    }

    private TTaskInfo auditTaskInfoCheckBaseInfo(TTaskInfoDto taskInfo) {
        Long id = taskInfo.getTaskId();
        if (Objects.isNull(id)){
            throw new ServiceException("审核信息不存在");
        }
        TTaskInfo t = taskInfoService.getById(id);
        if (Objects.isNull(t)){
            throw new ServiceException("审核信息不存在");
        }
        return t;
    }


    /**
     user_ask_rate2
     user_ask_rate3
     * 任务提交成功，处理用户金额逻辑
     * @param taskInfo
     * @param tUserTaskInfo
     */
    private void computeMoney(TTaskInfo taskInfo,TUserTaskInfo tUserTaskInfo) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        tUserTaskInfo.setAuditUserId(loginUser.getUserId());
        BigDecimal money = tUserTaskInfo.getMoney();
        Long userId = tUserTaskInfo.getUserId();
        // 给用户加钱 给2个上级加钱
        TUserInfo userInfo = userInfoService.getById(userId);
        // 添加一条收益记录
        taskHandler.shouyi(userId,money,1,"完成"+taskInfo.getTaskName());
        // 找到父类用户
        Long parentId = userInfo.getParentId();
        if (parentId!=null&&parentId>0){
            List<SysDictData> dictData = dictDataMapper.selectDictDataByType("user_ask_rate1");
            SysDictData sysDictData = dictData.get(0);
            TUserInfo p1 = userInfoService.getById(parentId);
            if (sysDictData!=null){
                taskHandler.shouyi(parentId,money.multiply(new BigDecimal(sysDictData.getDictValue())),2,userInfo.getUserNick()+"完成"+taskInfo.getTaskName());
            }
            if (p1.getParentId()!=null&&p1.getParentId()>0){
                List<SysDictData> dictData2 = dictDataMapper.selectDictDataByType("user_ask_rate2");
                SysDictData sysDictData2 = dictData2.get(0);
                TUserInfo p2 = userInfoService.getById(p1.getParentId());
                if (sysDictData2!=null){
                    taskHandler.shouyi(p1.getParentId(),money.multiply(new BigDecimal(sysDictData2.getDictValue())),2,userInfo.getUserNick()+"完成"+taskInfo.getTaskName());
                }
                if (p2.getParentId()!=null&&p2.getParentId()>0){
                    List<SysDictData> dictData3 = dictDataMapper.selectDictDataByType("user_ask_rate3");
                    SysDictData sysDictData3 = dictData3.get(0);
                    if (sysDictData2!=null){
                        taskHandler.shouyi(p2.getParentId(),money.multiply(new BigDecimal(sysDictData3.getDictValue())),2,userInfo.getUserNick()+"完成"+taskInfo.getTaskName());
                    }
                }
            }
        }

    }
}
